import React, { useState, useEffect } from "react";
import instance from '../axios/index'
import { message, Space } from 'antd';
import { Checkbox, Cell, Button } from '@nutui/nutui-react'
import { useNavigate, NavLink } from "react-router-dom";

import '../css/cart.css'
export default function Cart() {
  const navigate = useNavigate();
  const [goodlist, setGoodlist] = useState([]);
  const [messageApi, contextHolder] = message.useMessage();
  const [isAllChecked, setIsAllChecked] = useState(false);
  const [selectedIds, setSelectedIds] = useState([]);
  console.log(selectedIds);
  const [address, setAddress] = useState(localStorage.getItem('endAddress') || '河北省保定市莲池区北苑小区1号楼1单元101室')

  // 确认订单
  const handleClickOrders = () => {
    // alert(id)
    instance({
      url: `/cart/submit?ids=${selectedIds.join(',')}`
    })
      .then(res => {
        if (selectedIds.length > 0) {
          messageApi.open({
            type: 'success',
            content: '下单成功',
          });
          navigate(`/cart-orders/?ids=${selectedIds.join(',')}`)
        } else {
          messageApi.open({
            type: 'warning',
            content: '请选择您要购买的商品!!!',
          });
        }
      })
  }
  // 全选反选
  const handleClickCheckAll = () => {
    const newCheckedState = !isAllChecked;
    instance({
      url: `/cart/checkAll`,
      method: 'post',
      data: { isChecked: newCheckedState }
    }).then(res => {
      if (res.data.code === 200) {
        getlist()
      } else {
        alert(res.data.msg)
      }
    })
  }
  // 点击复选框进行选中
  const handleClickcheck = (_id) => {
    const newSelectedIds = selectedIds.includes(_id)
      ? selectedIds.filter(id => id !== _id)
      : [...selectedIds, _id];

    setSelectedIds(newSelectedIds); // 更新 selectedIds
    console.log(newSelectedIds);

    instance({
      url: `/cart/change?_id=${_id}`,
      method: 'post'
    }).then(res => {
      if (res.data.code === 200) {
        getlist()
      } else {
        alert(res.data.msg)
      }
    })
  }

  // 点击减号进行--
  const handleClickReduce = (_id) => {
    console.log(_id)
    instance({
      url: `/cart/reduce?_id=${_id}`,
    }).then(res => {
      if (res.data.code === 200) {
        getlist()
      } else {
        alert('最少选中一件商品')
      }
    })
  }
  // 点击加号进行++
  const handleClickAdd = (_id) => {
    console.log(_id)
    instance({
      url: `/cart/add?_id=${_id}`,
    }).then(res => {
      if (res.data.code === 200) {
        getlist()
      } else {
        alert('库存不足了，请等待补货')
      }
    })
  }
  const getlist = () => {
    instance({
      url: '/cart/goodlist'
    }).then(res => {
      const goods = res.data.goodlist;
      setGoodlist(goods)
      // 更新 selectedIds
      const updatedSelectedIds = goods
        .filter(item => item.isChecked) // 过滤出选中的商品
        .map(item => item._id); // 提取出商品 ID
      setSelectedIds(updatedSelectedIds);
      setIsAllChecked(goods.length > 0 && updatedSelectedIds.length === goods.length)
    })
  }
  useEffect(() => {
    getlist()
  }, [])

  const handleClickDelete = (_id) => {
    instance({
      url: `/cart/delete?_id=${_id}`
    }).then(res => {
      if (res.data.code === 200) {
        getlist()
        messageApi.open({
          type: 'success',
          content: '删除成功',
        });
      }
    })
  }


  return <div className="cartbigbox">
    {contextHolder}
    <div className="cartTopbox">
      <p style={{ fontSize: '20px', fontWeight: 'bold', color: 'white' }}>
        🛒购物车
      </p>
      <p>
        门店地址：{address}
      </p>
    </div>
    <div className="cartMiddlebox">
      {
        goodlist.map(item => (
          <div className="cartItembox" key={item._id}>
            <Cell className="nut-cell" style={{ width: '22px', textAlign: 'center', paddingLeft: '0px' }}>
              <Checkbox
                style={{ '--nut-icon-width': '20px', '--nut-icon-height': '100%' }}
                checked={item.isChecked}
                onChange={() => handleClickcheck(item._id)}
              />
            </Cell>
            <NavLink to={`/cate/?_id=${item._id}`}>
              <img src={item.img} alt="" />
            </NavLink>
            <div className="cartItemrightbox">
              <p style={{ position: 'relative' }}>{item.name}
                <button style={{ position: 'absolute', right: '10px', top: '25px', color: 'red', fontSize: '14px' }}
                  onClick={() => handleClickDelete(item._id)}>X</button>
              </p>
              <div className="cartItemrightbox2">
                <span>￥{item.price}</span>
                <p>
                  <button onClick={() => handleClickReduce(item._id)}>-</button>
                  <input type="text" value={item.num} />
                  <button onClick={() => handleClickAdd(item._id)}>+</button>
                </p>
              </div>
            </div>
          </div>
        ))
      }
    </div>
    <div className="cartBottombox">
      {/* <p> */}
      <Cell className="nut-cell" style={{ width: '80px', textAlign: 'center', paddingLeft: '0px' }}>
        <Checkbox
          style={{ '--nut-icon-width': '20px', '--nut-icon-height': '100%' }}
          label="全选"
          onChange={handleClickCheckAll}
          checked={isAllChecked}
        />
      </Cell>
      {/* </p> */}
      <p>
        <span style={{ fontWeight: 'bold' }}>合计:</span>
        <span style={{ fontWeight: 'bold', color: 'red', fontSize: '20px' }}>￥{goodlist.reduce((pre, cur) => {
          return cur.isChecked ? pre + cur.price * cur.num : pre;
        }, 0)}</span>
      </p>
      <Button type="primary" onClick={handleClickOrders}>
        结算
      </Button>
    </div>
  </div>;
}